/**
 * 系统后台数据库连接配置JS-systemDataSource.jsp
 */

//项目路径
var strPath = window.document.location.pathname;
var postPath = '/gdp';
var editStart = 1;//1添加、2修改


//内容初始化
function cleanContent() {
    $("#valide_dbKey").html("");
    $("#valide_dbMark").html("");
}


function showMsg(text, icon) {
    $.toast().reset('all');
    $.toast({
        text: text,
        icon: icon,
        showHideTransition: 'fade',
        allowToastClose: true,
        hideAfter: 1500,
        stack: false,
        position: 'top-right',
        textAlign: 'left',
        loader: true,
        loaderBg: '#9ec600',
    });
}


function confirmDelete(message, confirmFunction){
    var messageObj = {
        title: '确认删除？',
        message: message ,
        callback: confirmFunction
    }
    bootbox.confirm(messageObj);
}

var app = new Vue({
    el: '#main-container',
    data: {
        dic: {
            versionDic: [
                {code: 'ORACLE',name :'Oracle', driver:'oracle.jdbc.driver.OracleDriver'},
                {code: 'SQLSERVER',name :'SQL Server', driver:'com.microsoft.sqlserver.jdbc.SQLServerDriver'},
                {code: 'MYSQL',name :'MySQL', driver:'com.mysql.cj.jdbc.Driver'},
                {code: 'POSTGRESQL',name :'PostgreSQL', driver:'org.postgresql.Driver'},
                {code: 'TBASE',name :'TBASE', driver:'org.postgresql.Driver'},
                {code: 'KingbaseV8',name :'KingbaseV8', driver:'com.kingbase8.Driver'},
                {code: 'DM8',name :'达梦数据库', driver:'dm.jdbc.driver.DmDriver'},
                {code: 'MongoDB',name :'MongoDB', driver:''},
                {code: 'KUDU',name :'Kudu', driver:'com.cloudera.impala.jdbc41.Driver'},
            ]
        },
        dbConfig:{},
    },
    computed: {},

    created: function () {
    },

    mounted: function () {
        $("#tb_dataList").bootstrapTable({
            url: postPath + '/system/dataSource/list',
            undefinedText: '-',
            pagination: true, // 分页
            striped: true, // 是否显示行间隔色
            queryParams: function (pageReqeust) {
                var temp = {
                    order: pageReqeust.order,
                    pageNo: pageReqeust.offset / pageReqeust.limit + 1,
                    pageSize: pageReqeust.limit,
                    seachTxt: $("#searchTxt").val()
                };
                return temp;
            },
            cache: false, // 是否使用缓存
            pageList: [5, 10, 20],
            toolbar: "",// 指定工具栏
            showColumns: false, // 显示隐藏列
            showRefresh: false, // 显示刷新按钮
            uniqueId: "dbKey", // 每一行的唯一标识
            sidePagination: "server", // 服务端处理分页
            columns: [{
                field: 'state',
                checkbox: true,
                align: 'center',
                valign: 'middle'
            },  {
                title: '数据源名称',
                field: 'dbMark',
                align: 'center',
                valign: 'middle',
                sortable: false
            },{
                title: '数据源编码',
                field: 'dbKey', // 字段
                align: 'center', // 对齐方式（左 中 右）
                valign: 'middle', //
                sortable: false
            }, {
                title: '连接地址',
                field: 'dbIp',
                align: 'left',
                valign: 'middle',
                sortable: false,
                cellStyle: function (value, row, index) {
                    return {
                        css: {
                            "min-width": "80px",
                            "white-space": "nowrap",
                            "text-overflow": "ellipsis",
                            "overflow": "hidden",
                            "max-width": "220px"
                        }
                    }
                },
                formatter: function (value, row, index) {
                    if (!value) return null;
                    var span = document.createElement('span');
                    span.setAttribute('title', value);
                    span.innerHTML = value;
                    return span.outerHTML;
                }
            }, {
                title: '数据库名',
                field: 'dbName',
                align: 'center',
                valign: 'middle',
                sortable: false
            }, {
                title: '登录名',
                field: 'dbUser',
                align: 'center',
                valign: 'middle',
                sortable: false
            }, {
                title: '数据库版本',
                field: 'dbVersion',
                align: 'center',
                valign: 'middle',
                sortable: false
            },{
                title: '数据库驱动',
                field: 'dbDrivername',
                align: 'left',
                valign: 'middle',
                sortable: false,
            }

            ]
        });

    },
    methods: {
        /**
         * 新增
         */
        add: function () {
            cleanContent();
            this.dbConfig = {
                dbKey: '',
                dbMark: '',
                dbVersion: '',
                optType: 'HOST',
                dbIp: '',
                dbPort: '',
                dbName: '',
                dbSchema: '',
                dbUrl:'',
                dbDriverName: '',
                dbUser: '',
                dbPwd: '',
                ext1: 'SID',
            };
            $("#EditContent").modal('show');
            editStart = 1;
        },
        /**
         * 编辑
         */
        edit: function () {
            var _this = this;
            cleanContent();
            var row = $('#tb_dataList').bootstrapTable('getSelections');
            if (row == null || row == "") {
                bootbox.alert("请选择一行!");
                return;
            }
            if (row.length > 1) {
                bootbox.alert("只能选择一行修改!");
                return;
            }
            $.ajax({
                type: 'POST',
                url: postPath + '/system/dataSource/selectBykey',
                async: false,
                data: {key: row[0].dbKey},
                success: function (res) {
                    _this.dbConfig = {
                        dbKey: res.dbKey,
                        dbMark: res.dbMark,
                        dbVersion: res.dbVersion,
                        optType: res.optType ? res.optType : 'HOST',
                        dbIp: res.dbIp,
                        dbPort: res.dbPort,
                        dbName: res.dbName,
                        dbSchema: res.dbSchema,
                        dbUrl: res.dbUrl,
                        dbDriverName: res.dbDrivername,
                        dbUser: res.dbUser,
                        dbPwd: res.dbPwd,
                        ext1: res.ext1,
                    };
                    editStart = 2;
                    $("#dbKey").attr("readonly", "readonly");
                }
            });
            $("#EditContent").modal('show');
        },
        /**
         * 删除
         */
        del: function () {
            var row = $('#tb_dataList').bootstrapTable('getSelections');
            if (row == null || row == "") {
                bootbox.alert("请选择一行!");
                return;
            }

            var deleteFunction = function (result) {
                if (result == false)
                    return;
                var keys = "";
                $.each(row, function (i, e) {
                    keys += e.dbKey + ",";
                });
                keys = keys.substring(0, keys.length - 1);
                $.ajax({
                    url: postPath + '/system/dataSource/delData',
                    type: 'POST',
                    data: {keys: keys, isCheck: true},
                    success: function (res) {
                        if (res == -1) {
                            // bootbox.alert("请先删除元数据配置表信息!");
                            bootbox.prompt({
                                title: "警告：存在服务配置！继续操作请输入 “删除”",
                                callback: function (result) {
                                    if (result.trim() == "删除") {
                                        $.ajax({
                                            url: postPath + '/system/dataSource/delData',
                                            type: 'POST',
                                            data: {keys: keys, isCheck: false},
                                            success: function (res) {
                                                if (res != -1) {
                                                    showMsg("删除成功!", "success");
                                                    $('#tb_dataList').bootstrapTable('refresh');
                                                }
                                            }
                                        });
                                    } else {
                                        showMsg("删除失败!", "error");
                                    }
                                }
                            });
                        } else {
                            showMsg("删除成功!", "success");
                            $('#tb_dataList').bootstrapTable('refresh');
                        }
                    },
                    error: function () {
                        showMsg("删除失败!", "error");
                    }
                });
            };


            var message = "";
            $.each(row, function (i, e) {
                message += e.dbKey + " " + e.dbMark + "<br/>";
            });

            confirmDelete(message, deleteFunction)
        },
        /**
         * 保存
         */
        save: function () {
            var _this = this;
            var validateResult = this.validateData();
            if (validateResult) {
                var editurl = "";
                if (editStart == 1) {
                    editurl = postPath + '/system/dataSource/add';
                } else if (editStart == 2) {
                    editurl = postPath + '/system/dataSource/update';
                }

                var cfgdb = _this.dbConfig;
                for (var i = 0; i < this.dic.versionDic.length; i++) {
                    if (_this.dbConfig.dbVersion == this.dic.versionDic[i].code) {
                        _this.dbConfig.dbDrivername =this.dic.versionDic[i].driver
                    }
                }
                //Oracle 特殊处理模式
                if (cfgdb.dbVersion == 'ORACLE'){
                    _this.dbConfig.dbSchema = _this.dbConfig.dbUser.toUpperCase();
                }
                $.ajax({
                    type: 'POST',
                    url: editurl,
                    async: false,
                    data: JSON.stringify(_this.dbConfig),
                    dataType: 'json',
                    contentType: "application/json",
                    success: function (res) {
                        if (res > 0) {
                            showMsg("保存成功", "success");
                            $('#tb_dataList').bootstrapTable('refresh');
                            $("#EditContent").modal('hide');
                        } else {
                            showMsg("保存失败,请刷新后重试!", "error");
                        }
                    }
                });
            }
        },
        /**
         * 查询
         */
        search: function () {
            $("#tb_dataList").bootstrapTable('refresh');
        },
        /**
         * 测试连接
         */
        testSource: function () {
            _this = this;
            var validateResult = this.validateData();
            if (validateResult == true) {
                var cfgdb = _this.dbConfig;
                for (var i = 0; i < this.dic.versionDic.length; i++) {
                    if (_this.dbConfig.dbVersion == this.dic.versionDic[i].code) {
                        _this.dbConfig.dbDrivername =this.dic.versionDic[i].driver
                    }
                }

                $.ajax({
                    type: 'POST',
                    url: postPath + '/system/dataSource/testDataSource',
                    async: false,
                    data: JSON.stringify(cfgdb),
                    dataType: 'json',
                    contentType: "application/json",
                    success: function (res) {
                        if (res) {
                            showMsg("连接成功!", "success");
                        } else {
                            showMsg("连接失败!", "error");
                        }
                    }
                });
            }
        },
        /**
         * 验证表单内容
         */
        validateData: function () {
            var _this = this;
            if (_this.dbConfig.dbKey == "") {
                $("#valide_dbKey").html("数据源标识不能为空!");
                return false;
            } else if (editStart == 1) {
                var result = 0;
                $.ajax({
                    type: 'POST',
                    url: postPath + '/system/dataSource/selectBykey',
                    async: false,
                    data: {key: _this.dbConfig.dbKey},
                    success: function (res) {
                        if (res && res.dbKey) {
                            result = 1;
                        } else {
                            result = 2;
                        }
                    }
                });

                if (result == 0) {
                    showMsg("网络异常,请刷新后重试!", "error");
                    return false;
                } else  if (result == 1) {
                    $("#valide_dbKey").html("数据源标识已存在!");
                    return false;
                } else {
                    $("#valide_dbKey").html("");
                }
            } else {
                $("#valide_dbKey").html("");
            }

            if (_this.dbConfig.dbMark == "" ) {
                $("#valide_dbMark").html("中文名称不能为空!");
                return false;
            } else {
                $("#valide_dbMark").html("");
            }
            return true;
        }
    }

});

